import React, { useState, useEffect, useRef } from "react";

const VoiceControlPanel: React.FC = () => {
    const [isListening, setIsListening] = useState(false);
    const [action, setAction] = useState<string | null>(null);
    const recognitionRef = useRef<SpeechRecognition | null>(null);

    useEffect(() => {
        // 检查浏览器是否支持 Web Speech API
        if ("webkitSpeechRecognition" in (window as any)) {
            recognitionRef.current = new (window as any).webkitSpeechRecognition();
            const recognition = recognitionRef.current;

            recognition.continuous = false;
            recognition.interimResults = false;
            recognition.lang = "zh-CN"; // 设置为中文

            // 处理识别结果
            recognition.onresult = (event: SpeechRecognitionEvent) => {
                const transcript = event.results[0][0].transcript.trim();
                console.log("识别结果:", transcript);
                setAction(transcript);
                setIsListening(false);

                // 根据语音指令执行动作
                handleVoiceCommand(transcript);
            };

            // 处理识别错误
            recognition.onerror = (event: SpeechRecognitionErrorEvent) => {
                console.error("语音识别错误:", event.error);
                let userFriendlyMessage = "语音识别出错";
                switch (event.error) {
                    case "no-speech":
                        userFriendlyMessage = "没有检测到语音输入。请确保你在说话并且环境安静。";
                        break;
                    case "audio-capture":
                        userFriendlyMessage = "无法访问麦克风。请检查麦克风权限和硬件。";
                        break;
                    case "not-allowed":
                        userFriendlyMessage = "未授权使用麦克风。请在浏览器设置中允许麦克风访问。";
                        break;
                    default:
                        userFriendlyMessage = `未知错误: ${event.error}`;
                }
                alert(userFriendlyMessage);
                setIsListening(false);
            };

            // 识别结束时可以提示用户
            recognition.onend = () => {
                console.log("语音识别结束");
                // 如果需要在结束时自动重启，可以在这里调用 setIsListening(true);
            };
        } else {
            console.error("Web Speech API 不被此浏览器支持");
            alert("抱歉，您的浏览器不支持语音识别功能。请使用最新版本的 Chrome 或基于 Chromium 的浏览器。");
        }

        return () => {
            if (recognitionRef.current) {
                recognitionRef.current.stop();
            }
        };
    }, []);

    const startListening = () => {
        if (!recognitionRef.current) return;

        setIsListening(true);
        try {
            recognitionRef.current.start();
        } catch (err) {
            console.error("启动语音识别失败:", err);
            setIsListening(false);
            alert("启动语音识别失败，请确保麦克风可用并重试。");
        }
    };

    const handleVoiceCommand = (command: string) => {
        // 根据语音指令映射到小维的动作
        switch (command) {
            case "你好":
                console.log("小维: 你好！");
                // 触发动作1
                break;
            case "跳舞":
                console.log("小维: 开始跳舞！");
                // 触发动作2
                break;
            case "停止":
                console.log("小维: 停止动作！");
                // 触发动作3
                break;
            default:
                console.log("小维: 不明白你的意思");
                alert("小维: 不明白你的意思");
                break;
        }
    };

    return (
        <div style={{ padding: "20px", fontFamily: "Arial" }}>
            <h1>小维语音控制面板</h1>
            <p>点击按钮开始语音识别：</p>
            <button onClick={startListening} disabled={isListening}>
                {isListening ? "正在聆听..." : "开始语音识别"}
            </button>

            {action && <p>你说的是: {action}</p>}
        </div>
    );
};

export default VoiceControlPanel;